package yunhe.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;

public class NewsUtil {

	/**
	 * 输入字符串转化为32位的MD5字符串返回
	 * 
	 * @param str
	 * @return
	 */
	public static String str2md5(String str) {
		String s = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(str.getBytes("UTF-8"));
			byte[] m = md5.digest();
			StringBuilder sb = new StringBuilder();
			for (byte b : m) {
				int bb = Byte.toUnsignedInt(b);

				if (bb <= 0xf) {
					sb.append(0);
				}
				sb.append(Integer.toHexString(bb));
			}
			s = sb.toString();
		} catch (Exception e) {
			s = null;
		}

		return s;
	}

	/**
	 * 根据name获取value
	 * 
	 * @param request
	 * @param name
	 * @return
	 */

	public static String getValue(Cookie[] cookies, String name) {

		if (cookies != null && cookies.length > 0) {
			for (Cookie c : cookies) {
				if (c.getName().equals(name)) {
					return c.getValue();
				}
			}
		}

		return "";
	}

	/**
	 * 新加cookie
	 * 
	 * @param response
	 * @param cookie
	 */
	public static void addCookies(HttpServletResponse response,
			Cookie[] cookies, int maxAge) {
		for (Cookie c : cookies) {
			c.setMaxAge(maxAge);
			response.addCookie(c);
		}
	}
}
